package com.eden.api.utils;

import com.eden.common.exception.BusinessException;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Properties;

/**
 * @author wenqing
 * @version 2019年6月24日 上午9:40:12
 *
 */
public class PropertyReader {

    public static String getValue(String configLocation, String key, boolean check) {
        InputStream is = null;
        try {
            Properties prop = new Properties();
            URL url = new URL(URLDecoder.decode(getURL(configLocation).toString(), "UTF-8"));
            String propertiesFile = url.getFile();
            is = new FileInputStream(propertiesFile);
            prop.load(is);
            if (prop.containsKey(key)) {
                return prop.getProperty(key);
            }else {
                if(check){
                    throw new BusinessException("配置文件" + propertiesFile + "不存在" + key
                            + "项配置");
                }else{
                    return null;
                }
            }
        } catch (FileNotFoundException e) {
            throw new BusinessException("配置文件" + configLocation + "不存在");
        } catch (IOException e) {
            throw new BusinessException("读取配置文件" + configLocation + "错误");
        } finally {
            if (is != null) {
                try {
                    is.close();
                    is = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static URL getURL(String resourceLocation)
            throws FileNotFoundException {
        if (resourceLocation.startsWith("classpath:")) {
            String path = resourceLocation.substring("classpath:".length());
            URL url = getDefaultClassLoader().getResource(path);
            if (url == null) {
                String description = "class path resource [" + path + "]";
                throw new FileNotFoundException(
                        description
                                + " cannot be resolved to URL because it does not exist");
            }
            return url;
        }
        try {
            return new URL(resourceLocation);
        } catch (MalformedURLException ex) {
            try {
                return new File(resourceLocation).toURI().toURL();
            } catch (MalformedURLException ex2) {
                throw new FileNotFoundException("Resource location ["
                        + resourceLocation
                        + "] is neither a URL not a well-formed file path");
            }
        }
    }

    public static ClassLoader getDefaultClassLoader() {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Throwable ex) {
        }
        if (cl == null) {
            cl = PropertyReader.class.getClassLoader();
        }
        return cl;
    }
}
